﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
public class OrganButton : MonoBehaviour
{
    public UnityEvent OnOrganOpen;
    public UnityEvent OnOrganClose;

    int enterTriggerCount = 0;
    float startY;
    float endY;
    private void Awake()
    {
        startY = transform.position.y;
        endY = transform.position.y - transform.localScale.y / 2 + 0.1f;
    }
    IEnumerator Move(float target)
    {        
        float timer = 0f;
        Vector3 pos = transform.position;
        while (timer < 0.2f)
        {
            timer += Time.deltaTime;
            pos.y = Mathf.Lerp(pos.y, target, timer * 2f);
            transform.position = pos;
            yield return new WaitForEndOfFrame();
        }
        pos.y = target;
        transform.position = pos;
    }
    public void OnTriggerEnter2D(Collider2D other)
    {
        enterTriggerCount++;
        if (enterTriggerCount == 1)
        {
            OnOrganOpen.Invoke();
            StopAllCoroutines();
            StartCoroutine(Move(endY));
        }
    }
    public void OnTriggerExit2D(Collider2D other)
    {
        enterTriggerCount--;
        if (enterTriggerCount == 0)
        {
            OnOrganClose.Invoke();
            StopAllCoroutines();
            StartCoroutine(Move(startY));
        }
    }
}
